package com.blue.http.filter;

import com.blue.http.config.ErrorConfig;
import com.blue.http.controller.Authorized;
import com.blue.http.filter.Filter;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.HttpResponse;
import com.blue.http.util.HttpException;

import javax.annotation.Resource;

/**
 * 权限验证过滤器
 *
 * @author Jin Zheng
 * @date 2018-10-29
 */
public class AuthorizedFilter implements Filter
{
	@Resource
	private Authorized authorized;
	private ErrorConfig errorConfig = ErrorConfig.getInstance();

	public AuthorizedFilter()
	{
	}

	@Override
	public boolean preHandle(HttpRequest request, HttpResponse response) throws HttpException
	{
		String token = request.getQueryString("token");
		if (token == null || token.isEmpty())
		{
			response.setCode(ErrorConfig.PARAM);
			response.setMsg(errorConfig.get(response.getCode()));
			response.setExtmsg("令牌不能为空");
			return false;
		}
		boolean auth = authorized.auth(token, request.getUrl());
		if (!auth)
		{
			response.setCode(ErrorConfig.AUTH);
			response.setMsg(errorConfig.get(response.getCode()));
		}

		return auth;
	}

}
